<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Auction
 * @version 	: 1.1
 * COPYRIGHT    : 2010
 * ------------------------------------------------------
 *
 * Created on	:  Sep 13, 2010
 *
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );
RClassesImporter::cls('controllers.AbstractBackEndController');

/**
 * The controller for image application
 *
 */
class ImageBackController extends AbstractBackEndController {
	/**
	 * 
	 * Main model
	 * @var ImageModel
	 */
	var $_model;
	
	/**
	 * 
	 * Constructor
	 */
	function __construct() {
		parent::__construct();
		SysApplication::importModelCls('ImageModel');
		$this->_model = new ImageModel();
		$this->registerTask ( "new", "edit" );
		$this->registerTask ( "apply", "save" );

		$this->registerTask ( "multiupload", "multiuploadfile" );
		//		$this->_tmpFolder = 'files/cliparts/tmp/'.session_id()."_".SysAuthenticate::getUserId();
		$this->_tmpFolder = 'files/tmp/';
	}

	/**
	 * (non-PHPdoc)
	 * @see src/core/mvc/AbstractController::display()
	 */
	function display() {
		$this->setTitle (SysLanguage::_('Images Management'));
		$this->addToolbarButton ( "new" );
		$this->addToolbarButton ( "edit" );
		$this->addToolbarButton ( "delete" );
		$this->addToolbarButton ( "multiupload", 'Upload');
		$msg = SysRequest::getVar ( "msg" );

		RCoreImporter::cls( "html.TableControl" );
		RClassesImporter::cls("dbo.views.ImageViewDTO" );

		$table = new TableControl ( 'ImageViewDTO', NULL, $_REQUEST, 'ImageCtrl', '', '' );
		//TableControl($dtoName, $arrayViewField, $arrayRequest, $name, $where, $orderBy, $db=null)
		$nextExec = $this->getExecuteBy();
		$nextExec = ucfirst($nextExec);

		$table->setFieldHtmlInfo('image', $this->_getImageFieldInfo('image', '*.gif, *.jpg, *.png'));
		$table->setLinkRule("name", 'javascript:edit'.$nextExec.'Item($key)');
		$table->setLinkRule('add_date', 'javascript:edit'.$nextExec.'Item($key)');
		$table->setFieldHtmlInfo('album_id',$this->_getAlbumField());

		$table->removeField('image_id');
		$table->removeField('album_id');
		$tblHtml = $table->createHtmlTable(SystemSite::getSiteConfig()->list_limit);
		eval('echo "'.SysApplication::loadTemplate('back/listImage').'";');
	}

	/**
	 * 
	 * Edit dto
	 * @param ImageDTO $dto
	 */
	function edit($dto = null) {
		$oModel = $this->_model;
		$cid = SysRequest::getVar ( "cid" );
		if (empty( $dto )) {
			if(is_array($cid)) {
				$cid = $cid[0];
			}
			$dto = $oModel->getImageDetails($cid);
		}
		$formData = $this->_getEditFormAndPrepareEditTask($dto, 'Image', true);
		$formData->setFieldHtmlInfo('album_id',$this->_getNewsCbxFieldInfo('album_id'));
		$formData->setFieldHtmlInfo('image',$this->_getPicFileFiledInfo('image'));
		$formData->setFieldHtmlInfo('add_date',$this->_getDateHtmlFieldInfo("add_date"));
		$htmlContent .= $formData->generateHtml();
		$msg = SysRequest::getVar('msg');
		eval('echo "'.SysApplication::loadTemplate('back/editImage').'";');
	}
	
	/**
	 * 
	 * Multiupload for images
	 * @param ImageDTO $dto
	 */
	function multiuploadfile ($dto = null) {
		$this->setTitle ( SysLanguage::_('MULTI_UPLOAD') );
		$this->addToolbarButton ( "multiSave" );
		$this->addToolbarButton ( "cancel" );

		$msg = SysRequest::getVar ( "msg" );
		$model = $this->_model;

		if (empty ( $dto )) {
			if (empty ( $id )) {
				$cid = SysRequest::getVar ( "cid" );
				if (is_array ( $cid )) {
					$id = $cid [0];
				} else {
					$this->setTitle ( SysLanguage::_('NEW_TITLE') );
				}
				$dto = $model->getImageDetails ( $id );
			}
		}
		if ($dto->hasError ()) {
			$msg = $dto->getAllErrorsMsg ();
		}
		$formData = $this->_getEditFormMutiupload ( $dto );

		$folderfiles = SYS_ROOT_URL .$this->_tmpFolder;
		$folderfilesPath = SYS_ROOT_PATH.$this->_tmpFolder;
		RFileFolderHelper::checkAndCreateFolder($folderfilesPath);

		$htmlContent = $formData->generateHtml ();
		$htmlHidden = '<input type="hidden" name="id" value="' . $dto->id . '"/>';
		$tplUrl = SYS_ROOT_URL."ext/Multiupload/";
		$folderImage = $folderfiles."/";
		$sessionId = addslashes($folderfilesPath) ."/";
		eval ( 'echo "' . SysApplication::loadTemplate ( 'back/multiupload' ) . '";' );
	}

	/**
	 * 
	 * Build edit form
	 * @param ImageDTO $dto
	 */
	function &_getEditFormMutiupload ($dto) {
		RCoreImporter::cls ( "html.FormFieldsControl" );

		$formData = new FormFieldsControl ($dto);
		$formData->setFieldHtmlInfo('album_id', $this->_getArtCatHtmlInfo());
	
		$formData->insertFieldHtmlInfo('ClipArts',
				"<div id='swfupload-control'><input type='button' id='mybutton' /><br/><br/><span>Maximum 200 files, each file's size must be less than 1M</span>
				<p id='queuestatus' ></p>
				<ol id='log'></ol></div>");
		$expectedArray = array ('album_id', 'ClipArts');
		$formData->setExpectedArrange ( $expectedArray );

		return $formData;
	}
	
	/**
	 * 
	 * Build dropdown box for Albums
	 * @param string $inputName
	 * @param array $arrayOrObject
	 */
	function &_getArtCatHtmlInfo($inputName = "album_id", $arrayOrObject = null) {
		if (empty($arrayOrObject)) {
			$arrayOrObject = $_POST;
		}
		return $this->_getNewsCbxFieldInfo($inputName);
	}
	
	/**
	 * 
	 * Save for multiupload function
	 */
	function multiSave() {
		$model = $this->_model;
		$dto = new ImageDTO();
		$dto->bind($_POST);
		$dto->setEmptyToNull();
		$cateId = $_POST['album_id'];

		if(is_array($_POST['album_id'])) {
			$cateId = $_POST['album_id'][0];
		}

		if (!$cateId) {
			$_path = "files/images/album/";
			$_thumbPath = "files/images/album/";
		}
		else {
			$_path = "files/images/album/{$cateId}/";
			$_thumbPath = "files/images/album/{$cateId}/";
		}
		RFileFolderHelper::checkAndCreateFolder($_path);
		RFileFolderHelper::checkAndCreateFolder($_thumbPath);
		$file = $this->_getImageFieldInfo('file', '*.gif, *.jpg, *.png');
		$thumb = $this->_getImageFieldInfo('thumb');
		$dto->file = $file->getUploadedFilePath($_path);
		$dto->thumb = $thumb->getUploadedFilePath($_thumbPath);
		$thumbFile = $_thumbPath.RFileFolderHelper::getFileName($dto->file);
		if(!$dto->thumb) {
			@copy(SYS_ROOT_PATH.$dto->file, SYS_ROOT_PATH.$thumbFile);
			$dto->thumb = $thumbFile;
		}
		if ( $dto->file != "") {
			$dto->album_id = $cateId;
			if ($file->hasUpdate()) {
				$fileName = RFileFolderHelper::getFileName($dto->file);
				$fileName = RFileFolderHelper::removeExtension($fileName);
				$fileName = RStringHelper::cleanSubUnderScore($fileName);
				if (!$dto->name) {
					$dto->name = $fileName;
				}
				$dto->keywords = $fileName;
			}
			if($thumb->hasUpdate() == false) {
				if(!$dto->thumb) {
					$dto->thumb = $thumbFile;
				}
			}
			SysDatabase::saveDTO($dto);
			if ($dto->hasError ()) {
				$msg = $dto->getAllErrorsMsg ();
				return $this->edit ( $dto );
			}
			$mapping = $model->getAlbumImageMapping($dto);
			$mapping->im_id = $dto->image_id;
			$mapping->bind($_POST);
			$mapping->save();
		} else {
			$dto = new ImageDTO();
			$folderTemp = SYS_ROOT_PATH.$this->_tmpFolder;
			RFileFolderHelper::checkAndCreateFolder($_path);
			$handle = opendir($folderTemp);
			$file = readdir($handle);
			while(($file = readdir($handle)) !== false) {
				if($file != '.' && $file != '..' && $file!= 'Thumbs.db') {
					$fileName = RFileFolderHelper::getFileName($file);
						
					//$fileName = @base64_decode($fileName);
					$desFile = RFileFolderHelper::getBestFileName($_path, $fileName);
					$fileName = RFileFolderHelper::removeExtension($fileName);

					$dto->name = $fileName;
					$dto->image = $_path.$desFile;
					$result = copy($folderTemp. $file,SYS_ROOT_PATH. $_path .$desFile);
					if ($result) {
						$dto->file = $_path .$desFile;
						RFileFolderHelper::checkAndCreateFolder($_thumbPath);
						$thumbFile = $_thumbPath.RFileFolderHelper::getFileName($dto->file);

						copy(SYS_ROOT_PATH.$dto->file, SYS_ROOT_PATH.$thumbFile);

						$dto->thumb = $thumbFile;
						if (SysDatabase::saveDTO($dto) && $cateId) {
							$sql = "INSERT INTO album_image_map (al_id, im_id)
										VALUES ({$dto->image_id}, {$cateId})";
							SysDatabase::execute($sql);
						}
					}
					@unlink($folderTemp.$file);
				}
				$dto = new ImageDTO();
				$dto->bind($_POST);
				$dto->setEmptyToNull();
			}

			if ($handle == true) {
				@closedir($handle);
				@rmdir($folderTemp);
			}
		}
		if ($result === false || $this->getExecuteVal () == 'apply') {
			if($result === false) {
				$msg = ($msg != NULL) ? $msg : SysLanguage::_('ITEM_SAVE_FAILED');
			}
			$_REQUEST ["msg"] = $msg ? $msg : SysLanguage::_ ( "ITEM_SAVE_SUCCESSFUL" );
			return $this->edit ( $dto );
		} else {
			$this->setRedirectToFunction ( 'display', $msg ? $msg : SysLanguage::_ ( "ITEM_SAVE_SUCCESSFUL" ) );
		}
	}
	
	/**
	 * 
	 * Save dto
	 * @param boolean $isImageEdit
	 */
	function save($isImageEdit = false) {
		$model = $this->_model;
		$dto = new ImageDTO();
		if (SysRequest::getInt('id')) {
			$dto->resetToNull();
		}
		$dto->bind($_POST);
		if ($dto->checkKeyNotDefault()) {
			$dto->setEmptyNumberToZero();
		}

		$picField = $this->_getPicFileFiledInfo('image');
		$dto->image = $picField->getUploadedFilePath('files/images');
		$result = $model->saveImageDTO ( $dto );
		if ($dto->hasError())
		$msg = $dto->getAllErrorsMsg();

		if ($result === false || $this->getExecuteVal () == 'apply') {
			$_REQUEST ["msg"] = $msg ? $msg : SysLanguage::_ ( "ITEM_SAVE_SUCCESSFUL" );
			return $this->edit ($dto);
		} else {
			$this->setRedirectToFunction('display', $msg ? $msg : SysLanguage::_ ( "ITEM_SAVE_SUCCESSFUL" ));
		}
	}
	
	/**
	 * 
	 * Build image field
	 * @param string $inputName
	 */
	function &_getPicFileFiledInfo($inputName) {
		RCoreImporter::cls( "html.fieldInfo.FlashFileHtmlFieldInfo" );
		$field = new FlashFileHtmlFieldInfo($inputName,$linkRule);
		$field->setSupportedFilteType('.jpg,.jpeg,.bmp,.png,.gif');
		return $field;
	}
	
	/**
	 * 
	 * Delete image
	 */
	function delete() {
		$model = $this->_model;
		$arrayIds = SysRequest::getVar ( "cid" );
		$model->delete($arrayIds);
		$this->setRedirectToFunction('display', SysLanguage::_ ( "ITEM_DELETE_SUCCESSFUL" ));
	}
	
	/**
	 * 
	 * Build dropdown box for albums
	 * @param AbstractFieldInfo $info
	 */
	function &_getNewsCbxFieldInfo($info) {
		$sql = "SELECT album_id, album_name FROM album";
		$info = &$this->_getSqlComboboxHtmlFieldInfo($info, $sql);
		if ($arrayOrObject) {
			$info->setValue($arrayOrObject);
		}
		return $info;
	}
	
	/**
	 * 
	 * Unknown
	 */
	function &_getAlbumField() {
		$sql = "SELECT album_id, album_name FROM album";
		$info = SysDatabase::loadObject($sql);
		return $info->album_name;
	}

}
?>